package com.party.mobile.web.controller.mall;

import com.google.common.base.Function;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.mall.MallShowCategoryWithGoods;
import com.party.core.model.mall.MallShowSubject;
import com.party.core.model.mall.MallShowSubjectTemplate;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.mall.IMallShowGoodsService;
import com.party.core.service.mall.IMallShowSubjectService;
import com.party.core.service.mall.IMallShowSubjectTemplateService;
import com.party.core.service.member.IMemberGroupService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.mall.output.MallShowSubjectListOutput;
import com.party.mobile.web.dto.mall.output.MallShowSubjectOutput;
import com.party.mobile.web.dto.mall.output.MallShowSubjectTemplateOutput;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 展示商品主题控制器
 * Created by wei.li
 *
 * @date 2017/8/24 0024
 * @time 17:16
 */

@Controller
@RequestMapping(value = "mall/show/subject")
public class MallShowSubjectController {

    @Autowired
    private IMallShowSubjectService mallShowSubjectService;

    @Autowired
    private IMallShowSubjectTemplateService mallShowSubjectTemplateService;

    @Autowired
    private CurrentUserBizService currentUserBizService;

    @Autowired
    private IMallShowGoodsService mallShowGoodsService;
    @Autowired
    private IMemberGroupService memberGroupService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 获取商品专题信息
     *
     * @param id 编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "get")
    public AjaxResult get(String id) {
        try {
            MallShowSubject mallShowSubject = mallShowSubjectService.get(id);
            if (null == mallShowSubject || mallShowSubject.getDelFlag().equals("1")) {
                return AjaxResult.error(PartyCode.IS_NO_DATA, "展示商品专题不存在");
            }
            mallShowSubject.setContent(StringEscapeUtils.unescapeHtml4(mallShowSubject.getContent()));
            mallShowSubject.setBuyInstruction(StringEscapeUtils.unescapeHtml4(mallShowSubject.getBuyInstruction()));

            MallShowSubjectOutput output = MallShowSubjectOutput.transform(mallShowSubject);

            MallShowCategoryWithGoods withGoods = new MallShowCategoryWithGoods();
            withGoods.setSubjectId(id);
            List<MallShowCategoryWithGoods> list = mallShowGoodsService.withCategoryListPage(withGoods, null);
            list.forEach(mallShowCategoryWithGoods -> mallShowCategoryWithGoods.getMallShowGoodsList().forEach(category -> {
                String url = category.getUrl();
                String newUrl = null;
                if (url.indexOf("http:") > -1) {
                    newUrl = url.substring("http:".length());
                } else if (url.indexOf("https:") > -1) {
                    newUrl = url.substring("https:".length());
                }
                if (StringUtils.isNotEmpty(newUrl) && !url.equals(newUrl)) {
                    String targetId = category.getTargetId();
                    Integer type = category.getType();
                    if (StringUtils.isNotEmpty(targetId) && null != type && StringUtils.isNotEmpty(id)) {
                        MallShowSubject mallShowSubject1 = mallShowSubjectService.get(id);
                        String memberId = mallShowSubject1.getMemberId();
                        if (StringUtils.isNotEmpty(memberId)) {
                            newUrl += "?disId=" + memberId;
                        }
                    }
                    category.setUrl(newUrl);
                }
            }));
            output.setCategories(list);

            if (StringUtils.isNotEmpty(output.getTemplateId())) {
                MallShowSubjectTemplate template = mallShowSubjectTemplateService.get(output.getTemplateId());
                if (null != template) {
                    output.setTemplateIntroduction(template.getInstruction());
                }
            }
            return AjaxResult.success(output);
        } catch (Exception e) {
            logger.error("获取商品专题信息异常", e);
            return AjaxResult.error(100, "获取商品专题信息异常");
        }
    }

    /**
     * 获取商品模板的信息
     *
     * @param templateId 模板id
     * @return 模板信息
     */
    @ResponseBody
    @RequestMapping(value = "getTemplate")
    public AjaxResult getTemplate(String templateId) {
        try {
            MallShowSubjectTemplate mallShowSubjectTemplate = mallShowSubjectTemplateService.get(templateId);
            if (null == mallShowSubjectTemplate || BaseModel.DEL_FLAG_DELETE.equals(mallShowSubjectTemplate.getDelFlag())) {
                return AjaxResult.error(PartyCode.IS_NO_DATA, "展示商品专题不存在");
            }
            mallShowSubjectTemplate.setContent(StringEscapeUtils.unescapeHtml4(mallShowSubjectTemplate.getContent()));
            mallShowSubjectTemplate.setBuyInstruction(StringEscapeUtils.unescapeHtml4(mallShowSubjectTemplate.getBuyInstruction()));

            MallShowSubjectTemplateOutput output = MallShowSubjectTemplateOutput.transform(mallShowSubjectTemplate);

            MallShowCategoryWithGoods withGoods = new MallShowCategoryWithGoods();
            withGoods.setTemplateId(templateId);
            List<MallShowCategoryWithGoods> list = mallShowGoodsService.withCategoryListPage(withGoods, null);
            output.setCategories(list);

            MemberGroup member = memberGroupService.getTXZ();

            output.setPublisher(member.getRealname());
            output.setPublisherLogo(member.getLogo());
            output.setTemplateIntroduction(output.getInstruction());
            output.setInstruction("CEO户外活动服务平台，智者同行，践行共赢");

            return AjaxResult.success(output);
        } catch (Exception e) {
            logger.error("获取商品模板的信息", e);
            return AjaxResult.error(100, "获取商品模板的信息");
        }
    }

    /**
     * 我的专题列表
     *
     * @param request
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping("getMySubjectList")
    public AjaxResult getMySubjectList(HttpServletRequest request, Page page) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

            String memberId =  memberGroupService.getPartnerId(currentUser.getId());

            List<MallShowSubject> subjects = mallShowSubjectService.listPage(new MallShowSubject(memberId), page);
            List<MallShowSubjectListOutput> subjectListOutputs = LangUtils.transform(subjects, new Function<MallShowSubject, MallShowSubjectListOutput>() {
                @Nullable
                @Override
                public MallShowSubjectListOutput apply(@Nullable MallShowSubject input) {
                    MallShowSubjectListOutput output = new MallShowSubjectListOutput();
                    output.setId(input.getId());
                    output.setPic(input.getPic());
                    output.setName(input.getName());
                    return output;
                }
            });
            return AjaxResult.success(subjectListOutputs, page);
        } catch (Exception e) {
            logger.error("获取我的专题列表异常", e);
            return AjaxResult.error(100, "获取我的专题列表异常");
        }
    }
}
